package com.net.xpay.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * jwt
 */
public class JWTUtil {

    private static final String SIGN = "!P@HS3K#01tAK";

    /**
     * 生成token header.payload.sing
     * @param seconds 过期时间 单位秒
     * @param payload 负载
     * @return
     */
    public static String getToken(int seconds, Map<String, String> payload) {
        JWTCreator.Builder builder = JWT.create();
        payload.forEach(builder::withClaim);

        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, seconds);

        return builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(SIGN));
    }


    /**
     * 验证token
     * @param token token
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
    }

}